// import http from '../../g-server';

/**
 * 商品状态枚举
 */
export enum ProductStatus {
  Draft = 0,        // 草稿
  OnSale = 1,       // 在售
  OutOfStock = 2,   // 缺货
  Discontinued = 3, // 已下架
}

/**
 * 商品信息接口
 */
export interface Product {
  id: string | number;
  name: string;
  code: string;
  category?: string;
  price?: number;
  stock?: number;
  image?: string;
  description?: string;
  status?: ProductStatus;
  createTime?: string;
  updateTime?: string;
}

/**
 * 商品列表查询参数
 */
export interface ProductListParams {
  page: number;
  pageSize: number;
  keyword?: string;
  category?: string;
  status?: ProductStatus;
  minPrice?: number;
  maxPrice?: number;
  minStock?: number;
  maxStock?: number;
  startDate?: string;
  endDate?: string;
}

/**
 * 商品列表查询结果
 */
export interface ProductListResult {
  list: Product[];
  total: number;
}

/**
 * 商品服务类
 */
class ProductService {
  /**
   * 获取商品列表
   * @param params 查询参数
   */
  async getProductList(params: ProductListParams): Promise<ProductListResult> {
    // 实际项目中应该调用API
    // const response = await http.get('/product/list', { params });
    // return response.data;
    
    // 模拟数据
    const mockProducts: Product[] = [];
    
    // 生成随机商品数据
    for (let i = 1; i <= 50; i++) {
      mockProducts.push({
        id: i,
        name: `商品 ${i}`,
        code: `P${i.toString().padStart(6, '0')}`,
        category: i % 5 === 0 ? '电子产品' : i % 4 === 0 ? '服装' : i % 3 === 0 ? '家居' : i % 2 === 0 ? '食品' : '图书',
        price: Math.round(Math.random() * 1000 * 100) / 100,
        stock: Math.floor(Math.random() * 1000),
        image: i % 3 === 0 ? `https://picsum.photos/200/200?random=${i}` : undefined,
        description: `这是商品 ${i} 的详细描述，包含商品的各种信息。`,
        status: i % 10 === 0 ? ProductStatus.Discontinued : i % 7 === 0 ? ProductStatus.OutOfStock : i % 4 === 0 ? ProductStatus.Draft : ProductStatus.OnSale,
        createTime: new Date(Date.now() - i * 86400000).toISOString().split('T')[0],
        updateTime: new Date(Date.now() - i * 43200000).toISOString().split('T')[0],
      });
    }
    
    // 根据关键字过滤
    let filteredProducts = mockProducts;
    if (params.keyword) {
      const keyword = params.keyword.toLowerCase();
      filteredProducts = mockProducts.filter(
        product => 
          product.name.toLowerCase().includes(keyword) || 
          product.code.toLowerCase().includes(keyword)
      );
    }
    
    // 根据分类过滤
    if (params.category) {
      filteredProducts = filteredProducts.filter(product => product.category === params.category);
    }
    
    // 根据状态过滤
    if (params.status !== undefined) {
      filteredProducts = filteredProducts.filter(product => product.status === params.status);
    }
    
    // 根据价格范围过滤
    if (params.minPrice !== undefined) {
      filteredProducts = filteredProducts.filter(product => (product.price || 0) >= params.minPrice!);
    }
    
    if (params.maxPrice !== undefined) {
      filteredProducts = filteredProducts.filter(product => (product.price || 0) <= params.maxPrice!);
    }
    
    // 根据库存范围过滤
    if (params.minStock !== undefined) {
      filteredProducts = filteredProducts.filter(product => (product.stock || 0) >= params.minStock!);
    }
    
    if (params.maxStock !== undefined) {
      filteredProducts = filteredProducts.filter(product => (product.stock || 0) <= params.maxStock!);
    }
    
    // 根据创建时间范围过滤
    if (params.startDate) {
      const startDate = new Date(params.startDate).getTime();
      filteredProducts = filteredProducts.filter(product => {
        if (!product.createTime) return false;
        return new Date(product.createTime).getTime() >= startDate;
      });
    }
    
    if (params.endDate) {
      const endDate = new Date(params.endDate).getTime();
      filteredProducts = filteredProducts.filter(product => {
        if (!product.createTime) return false;
        return new Date(product.createTime).getTime() <= endDate;
      });
    }
    
    // 计算分页
    const total = filteredProducts.length;
    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;
    const list = filteredProducts.slice(start, end);
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return {
      list,
      total,
    };
  }

  /**
   * 获取商品详情
   * @param id 商品ID
   */
  async getProductDetail(id: string | number): Promise<Product> {
    // 实际项目中应该调用API
    // const response = await http.get(`/product/${id}`);
    // return response.data;
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return {
      id,
      name: `商品 ${id}`,
      code: `P${Number(id).toString().padStart(6, '0')}`,
      category: '电子产品',
      price: 999.99,
      stock: 100,
      image: `https://picsum.photos/200/200?random=${id}`,
      description: '这是一个示例商品的详细描述，包含商品的各种信息。',
      status: ProductStatus.OnSale,
      createTime: '2023-01-01',
      updateTime: '2023-01-15',
    };
  }

  /**
   * 创建商品
   * @param product 商品信息
   */
  async createProduct(product: Omit<Product, 'id'>): Promise<Product> {
    // 实际项目中应该调用API
    // const response = await http.post('/product', product);
    // return response.data;
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return {
      id: Math.floor(Math.random() * 1000) + 100,
      ...product,
      createTime: new Date().toISOString().split('T')[0],
      updateTime: new Date().toISOString().split('T')[0],
    };
  }

  /**
   * 更新商品
   * @param product 商品信息
   */
  async updateProduct(product: Product): Promise<Product> {
    // 实际项目中应该调用API
    // const response = await http.put(`/product/${product.id}`, product);
    // return response.data;
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return {
      ...product,
      updateTime: new Date().toISOString().split('T')[0],
    };
  }

  /**
   * 删除商品
   * @param id 商品ID
   */
  async deleteProduct(id: string | number): Promise<void> {
    // 实际项目中应该调用API
    // await http.delete(`/product/${id}`);
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 消除参数未使用的警告
    console.log(`删除商品ID: ${id}`);
  }

  /**
   * 获取商品分类列表
   */
  async getCategories(): Promise<string[]> {
    // 实际项目中应该调用API
    // const response = await http.get('/product/categories');
    // return response.data;
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 返回模拟数据
    return ['电子产品', '服装', '家居', '食品', '图书'];
  }
}

// 导出服务实例
export const productService = new ProductService();

// 为了兼容现有的content.tsx组件，添加ProductListApi导出
export const ProductListApi = productService; 